import 'dart:developer';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:scrollview_observer/scrollview_observer.dart';
import 'package:sports_new/server/api/record_api.dart';
import '../../entity/record/football/zq_schedule_entity.dart';
import '../../utils/utils.dart';
import '../../widgets/bottom_picker_widget.dart';
import 'channel_logic.dart';

class ScheduleLogic extends GetxController {
  final String? seasonTag;
  final int? leagueId;
  ScheduleLogic(this.leagueId, {this.seasonTag});

  late final channel = Get.find<ChannelLogic>(tag: seasonTag);
  List<ScheduleEntity>? data;
  String _round = "";
  bool visible = false;
  final ScrollController scrollC = ScrollController(initialScrollOffset: 36);
  late final ListObserverController observerController;
  int _currentItem = 0;
  final EasyRefreshController refreshController = EasyRefreshController();

  int get currentItem => _currentItem;
  String get round => _round;

  set round(String value) {
    _round = value;
    update();
  }
  set currentItem(int value) {
    if (value >= 0 && value < data!.length) {
      _currentItem = value;
    }
    update();
  }

  @override
  void onInit() async {
    await getData();
    initObserver();
    var currentSeason = channel.season;
    channel.addListener(() async{
      if (currentSeason != channel.season) {
        await getData(change: true);
        jump();
        currentSeason = channel.season;
      }
    });
    super.onInit();
  }

  Future getData({bool change = false}) async {
    data = await RecordApi.getSchedule(
      leagueId: leagueId,
      season: channel.season,
      seasonId: channel.seasonId,
      recordType: channel.recordType
    );
    var i = 0;
    if (round == "" || change) {
      data?.forEach((element) {
        if (element.isCurrent == 1 || i == (data?.length ?? 1) - 1) {
          _round = element.roundName!;
          _currentItem = i;
          return;
        }
        i++;
      });
    }
    if (_currentItem == 0 && data?.length != 0) {
      _round = data?[0].roundName ?? "";
    }
    log("当前轮$_round");
    update();
  }

  void initObserver() {
    if (data?.length != 0) {
      observerController = ListObserverController(controller: scrollC)
        ..cacheJumpIndexOffset = true
        ..initialIndexModel = ObserverIndexPositionModel(
            index: _currentItem,
            alignment: location()/((data?[_currentItem].schedules!.length ?? 0)+1));
    } else if (data?.length == 0) {
      observerController = ListObserverController()
        ..cacheJumpIndexOffset = true;
    }
    update();
  }

  void jump(){
    observerController.jumpTo(
      index: _currentItem,
      alignment: 0.8 / ((data?[_currentItem].schedules!.length ?? 0) + 1));
  }

  Future showDatePicker() async {
    RegExp regExp = RegExp(r"[0-9]");
    log("${regExp.hasMatch(data![0].roundName!)}");
    var result = await Get.bottomSheet(BottomPickerWidget(
      data!.map((e) => e.roundName!).toList(),
      title: '选择轮次',
      initialIndex: _currentItem,
    ));
    if (result != null) {
      Utils.onEvent("sjpd_sc_lcxz", params: {"sjpd_sc_lcxz": 1});
      _currentItem = result;
    } else {
      Utils.onEvent("sjpd_sc_lcxz", params: {"sjpd_sc_lcxz": 0});
    }
    update();
  }

  double location(){
    if(data?[_currentItem].matchLocation != null){
      return data![_currentItem].matchLocation! <= 2?0:data![_currentItem].matchLocation!-2;
    }
    return 0.8;
  }

  void doRefresh() {
    if(refreshController.headerState?.mode.isIdle == false) return;
    refreshController.callRefresh();
  }
}
